package com.houger.license;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.NetworkInterface;
import java.util.Base64;
import java.util.Enumeration;

public class HardwareFingerprint {

    private static final String HMACSECRET = "d2hhdHN5b3VybmFtZQ==";
    // 获取本机第一个有效MAC地址的哈希值
    public static String getMachineId() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface network = interfaces.nextElement();
                if (network.isLoopback() || network.isVirtual() || !network.isUp()) continue;
                
                byte[] mac = network.getHardwareAddress();
                if (mac != null && mac.length > 0) {
                    String rawData = Base64.getEncoder().encodeToString(mac);
                    return rawData + "|" + signWithHmac(rawData);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("无法获取硬件信息", e);
        }
        throw new RuntimeException("未找到有效网络接口");
    }

    public static String signWithHmac(String data) throws Exception {
        SecretKeySpec key = new SecretKeySpec(
            Base64.getDecoder().decode(HMACSECRET),
            "HmacSHA256"
        );

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(key);
        byte[] result = mac.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(result);
    }

}